import java.util.ArrayList;
import java.util.List;

public class MathUtil {
    private static int Dimension;
    private static int half;
    public MathUtil(int dimension){
        Dimension = dimension/2;
        half = Dimension/2 - 1;
    }

    public static List<Integer> DoubleToBinaryString(double count){
        List<Integer> list = new ArrayList<>();
        if(count <= 0) {
            list.add(1);
            list.add(0);
        }else{
            list.add(0);
            list.add(0);
        }
        int t = (int)count;
        double integer = (double)t;
        double decimal = count - integer;
        for(int i = 0; i < half; i++){
            int n = (int)Math.pow(2, half - i - 1);
            int temp = t/n;
            if(temp == 1){
                t -= n;
            }
            list.add(temp);
        }
        for(int i = 0; i < half; i++){
            decimal = decimal * 2;
            if(decimal >= 1){
                decimal -= 1;
                list.add(1);
            }else {
                list.add(0);
            }
        }
        return list;
    }

    public static double BinaryToDouble(List<Integer> list){
        double result = 0,integer = 0,decimal = 0;
        int sign = list.get(0);
        List<Integer> integerList = list.subList(2, half + 2);
        List<Integer> decimalList = list.subList(half + 2, Dimension);
        for(int i = 0; i < half; i++){
            integer += integerList.get(i)*Math.pow(2, half - i - 1);
            decimal += decimalList.get(i)/Math.pow(2, i + 1);
        }
        if(sign == 0) {
            result = integer + decimal;
        }else {
            result = -(integer + decimal);
        }
        return result;
    }

    public static List<Integer> concat(double x, double y){
        List<Integer> result = new ArrayList<>();
        List<Integer> xList = DoubleToBinaryString(x);
        List<Integer> yList = DoubleToBinaryString(y);
        int[] xArray = new int[xList.size()];
        int[] yArray = new int[yList.size()];
        for(int i = 0; i < xList.size(); i ++){
            xArray[i] = xList.get(i);
            yArray[i] = yList.get(i);
        }
        for(int i : xArray){
            result.add(i);
        }
        for(int i : yArray){
            result.add(i);
        }
        return result;
    }

    public static double[] divide(List<Integer> list){
        List<Integer> xList;
        List<Integer> yList;
        if(list.size() == 2*Dimension){
            xList = list.subList(0,Dimension);
            yList = list.subList(Dimension,Dimension*2);
        }else{
            return null;
        }
        double[] result = new double[2];
        result[0] = BinaryToDouble(xList);
        result[1] = BinaryToDouble(yList);
        return result;
    }

}